use leptos::prelude::*;
use shq_common::prelude::{ AndOr, FliterItem, Operator, User, WhereCause };
use thaw_utils::ArcOneCallback;
use crate::{components::{ButtonList, CommonPage, DataRange}, shhr::{del_home_visit_user, fetch_flow_run_step, fetch_user_by_dpid, save_home_visit_user, HomeVisitFile}, workflow::FlowRunList};
use shq_web_controls::{use_message,ToastPosition, ToasterProvider,MessageOptions,MessageVariant,};
use icondata as i;
use shq_web_controls::MultiTreeSelect;
use leptos_icons::*;
use serde_json::{ Map, Value };


#[component]
pub fn Jfyggl(menu_id: u32) -> impl IntoView {
    //接受选择的员工
    let selected_id = RwSignal::new(u32::default());
    let selected_fileid = RwSignal::new(u32::default());
    let selected_fileid2 = RwSignal::new(u32::default());
    let selected_emnm = RwSignal::new(String::new());
    let selected_emid = RwSignal::new(u32::default());
    let selected_dpid_run = RwSignal::new(u32::default());
    let selected_frid_run = RwSignal::new(u32::default());
    let selected_user_ids =  RwSignal::new(Vec::<String>::new());
    //获取本部门员工
    let curr_user = use_context::<RwSignal<Option<User>>>().unwrap();
    let dpid = curr_user.with(|u| u.as_ref().map(|u| u.dpid)).unwrap();
    let userid = curr_user.with(|u| u.as_ref().map(|u| u.id)).unwrap();
    let user_items = Resource::new(
        move || dpid,
        move |dpid| async move{ 
            let users = fetch_user_by_dpid(dpid).await;
            users
         }
    );
    //获取当前所在流程节点
    let stepids = Resource::new(
        move || selected_frid_run.get(),
        move |frid| async move{ 
            let stepid = fetch_flow_run_step(frid,userid).await;
            stepid
        }
    );

    //成功或者错误提示信息
    let mess = use_message();
    let error_message = RwSignal::new(None::<String>);
    let success_message = RwSignal::new(None::<String>);
    let saving = RwSignal::new(false);
    let is_refresh: RwSignal<bool> = RwSignal::new(false);
    // 新增模块的展示
    let showAddModel = RwSignal::new(false);
    // let showDelModel = RwSignal::new(false);
    let custom_specialist_mana = ArcOneCallback::new(move |_| {
        showAddModel.set(true)
    });
    //删除选中的员工
    let delete_user_action = Action::new(move |&(id): &(u32)| {
        // let id: u32 = selected_id.get();
        async move{
            error_message.set(None);
            saving.set(true);
            if  id == 0 {
                error_message.set(Some("请选择员工".to_string()));
                saving.set(false);
                return;
            }
            if stepids.get().and_then(|r| r.ok()) != Some(1){
                mess.create(
                    format!("删除失败！当前流程节点不是【发起家访】节点，不能删除员工！"),
                    MessageVariant::Error,
                    MessageOptions::default()
                );
                return;
            }
            match del_home_visit_user(id).await {
                Ok(_) => {
                    mess.create("删除成功", MessageVariant::Success, MessageOptions::default());
                    // showDelModel.set(false);
                    is_refresh.set(true);
                }
                Err(e) => {
                    mess.create(
                        format!("删除失败：{}", e),
                        MessageVariant::Error,
                        MessageOptions::default()
                    );
                }
            }
            saving.set(false);
        }
    });
    let delete_specialist_mana = ArcOneCallback::new(move |rows:Vec<Value>| {
        let row=rows[0].as_object().unwrap();
        let id=row.get("id").expect("返回值没有id");
        let id64=id.as_u64().expect("id不是u64类型");
        delete_user_action.dispatch(id64 as u32);
        // showDelModel.set(true)
    });
    // 定义自定义按钮
    let custom_buttons = {
        let mut bl = ButtonList::new();
        bl.add_custom(
            "新增".to_string(),
            Some(i::AiPlusCircleOutlined),
            None,
            None,
            DataRange::None,
            Vec::new(),
            custom_specialist_mana,
        );
        bl.add_custom(
            "删除".to_string(),
            Some(i::AiDeleteTwotone),
            None,
            Some("您确定要删除选择的员工吗？".to_string()),
            DataRange::Selected,
            vec!["id"],
            delete_specialist_mana,
        );
        bl
    };

    let on_change = move |values: Vec<String>| {
        selected_user_ids.set(values);
    };

    //保存家访员工数据
    let save_home_visit_empl_data = Action::new(move |_: &()| {
            let user_ids =selected_user_ids.get();
            let dpid_run =  selected_dpid_run.get();
            let frid_run =  selected_frid_run.get();
            async move {
                success_message.set(None);
                error_message.set(None);
                saving.set(true);
                let user_ids_result: Result<Vec<u32>, _> = user_ids.iter()
                .map(|id| id.parse::<u32>())
                .collect();

                let user_ids = match user_ids_result {
                    Ok(ids) => ids,
                    Err(e) => {
                        error_message.set(Some(format!("解析用户ID失败: {}", e)));
                        saving.set(false);
                        return;
                    }
                };
                if user_ids.len() != 0 {
                    match save_home_visit_user(user_ids,dpid_run,frid_run).await {
                        Ok(_) => {
                            mess.create("保存成功", MessageVariant::Success, MessageOptions::default());
                            is_refresh.set(true);
                        }
                        Err(e) => {
                            mess.create(
                                format!("保存失败：{}", e),
                                MessageVariant::Error,
                                MessageOptions::default()
                            );
                        }
                    }
                }
            }
        });

    //新增模块的展示
    let specialist_management = move || {
        if showAddModel.get() && stepids.get().and_then(|r| r.ok()) == Some(1) {
            Some(view! {
                <dialog id="data_import_modal" class="modal modal-open  z-50">
                    <div class="modal-box overflow-hidden max-w-md max-h-[80vh]">
                        <button class="absolute right-2 top-2" on:click=move|_|{
                            showAddModel.set(false);
                        }>
                            <Icon icon=i::AiCloseCircleOutlined width="20" height="20"/>
                        </button>
                        <h3 class="text-lg font-bold">新增家访员工</h3>
                        <div class="p-2">
                            <Suspense fallback=|| view! { <progress class="progress w-56"></progress> }>
                                {move || match user_items.get() {
                                    Some(Ok(user)) => {
                                        let tree_items = StoredValue::new(user.into());
                                        view! {
                                            <div class="flex-1 overflow-y-auto min-h-40 max-h-[calc(80vh-160px)]">
                                                <MultiTreeSelect
                                                    tree_items
                                                    show_confirm_cancel_btn=false
                                                    on_change
                                                    // height= 200
                                                />
                                            </div>
                                        }.into_any()
                                    }
                                    Some(Err(e)) => {
                                        view! {
                                            <div class="p-4 text-red-500">
                                                {e.to_string()}
                                            </div>
                                        }.into_any()
                                    }
                                    None => {
                                        view! {
                                            <div class="flex-1 flex items-center justify-center">
                                                "正在加载菜单数据..."
                                            </div>
                                        }.into_any()
                                    }
                                }}
                            </Suspense>
                            {/* 底部操作按钮 */}
                            <div class="mt-4 flex justify-end gap-2">
                                <button 
                                    class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                                    on:click=move|_| {
                                        showAddModel.set(false);
                                        save_home_visit_empl_data.dispatch(());
                                    }
                                >
                                    保存
                                </button>
                                <button 
                                    class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                                    on:click=move|_| {
                                        showAddModel.set(false);
                                    }
                                >
                                    取消
                                </button>
                                
                            </div>
                        </div>
                    </div>                    
                </dialog>
            })
        }else {
            None
        }
    };
    //删除模块的展示
    // let specialist_delete_management = move || {
    //     if showDelModel.get() {
    //         Some(
    //             view! {
    //             <dialog id="delete_confirm_modal" class="modal modal-open z-50">
    //                 <div class="modal-box max-w-md">
    //                     <button class="absolute right-2 top-2" on:click=move|_|{
    //                         showDelModel.set(false);
    //                     }>
    //                         <Icon icon=i::AiCloseCircleOutlined width="20" height="20"/>
    //                     </button>
    //                     <div class="flex items-center mb-4">
    //                         <Icon icon=i::AiExclamationCircleOutlined/>
    //                         <h3 class="text-lg font-bold">确认删除</h3>
    //                     </div>
    //                     <div class="p-2">
    //                         <p class="text-gray-700 mb-6">
    //                             "您确定要删除选中的家访员工吗？此操作不可撤销！"
    //                         </p>
    //                         {/* 底部操作按钮 */}
    //                         <div class="mt-4 flex justify-end gap-2">
    //                             <button 
    //                                 class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
    //                                 on:click=move|_| showDelModel.set(false)
    //                             >
    //                                 取消
    //                             </button>
    //                             <button 
    //                                 class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500"
    //                                 on:click=move|_| {
    //                                     showDelModel.set(false);
    //                                     delete_user_action.dispatch(());
    //                                 }
    //                             >
    //                                 确认删除
    //                             </button>
    //                         </div>
    //                     </div>
    //                 </div>
    //             </dialog>
    //         }
    //         )
    //     } else {
    //         None
    //     }
    // };

    // 获取选择行的内容
    let on_row_select_change = ArcOneCallback::new(
        move |selected_rows: Option<Map<String, Value>>| {
            if let Some(rows) = selected_rows {
                if let Some(Value::Number(id_value)) = rows.get("id") {
                    if let Some(int_id) = id_value.as_u64().map(|x| x as u32) {
                        selected_id.set(int_id);
                    }
                }
                if let Some(Value::Number(fileid1_value)) = rows.get("bfid1") {
                    if let Some(file1_id) = fileid1_value.as_u64().map(|x| x as u32) {
                        selected_fileid.set(file1_id);
                    }
                }
                if let Some(Value::Number(fileid2_value)) = rows.get("bfid2") {
                    if let Some(file1_id2) = fileid2_value.as_u64().map(|x| x as u32) {
                        selected_fileid2.set(file1_id2);
                    }
                }
                if let Some(Value::Number(emid)) = rows.get("emid") {
                    if let Some(value) = emid.as_u64().map(|x| x as u32) {
                        selected_emid.set(value);
                    }
                }
                if let Some(Value::String(emnm_value)) = rows.get("emnm") {
                    selected_emnm.set(emnm_value.clone());
                }
                // is_refresh.set(true);
            }
        }
    );

    let on_row_select_change_run = ArcOneCallback::new(
        move |selected_rows: Option<Map<String, Value>>| {
            if let Some(rows) = selected_rows {
                if let Some(Value::Number(dpid)) = rows.get("dpid") {
                    if let Some(value) = dpid.as_u64().map(|x| x as u32) {
                        selected_dpid_run.set(value);
                    }
                }
                if let Some(Value::Number(frid)) = rows.get("frid") {
                    if let Some(value) = frid.as_u64().map(|x| x as u32) {
                        selected_frid_run.set(value);
                    }
                }
            }
        }
    );

    let home_vist_file = move || {
        let selected_emnm = RwSignal::new(Some(selected_emnm.get()));
        let selected_emid = RwSignal::new(Some(selected_emid.get()));
        let selected_id = RwSignal::new(Some(selected_id.get()));
        let selected_fileid = RwSignal::new(Some(selected_fileid.get()));
        let selected_fileid2 = RwSignal::new(Some(selected_fileid2.get()));
        let selected_frid_run = RwSignal::new(selected_frid_run.get());

        view! {
            <HomeVisitFile 
                emnm=selected_emnm
                emid=selected_emid
                frid=selected_frid_run
                home_visit_empl_id=selected_id 
                home_visit_empl_fileid1=selected_fileid
                home_visit_empl_fileid2=selected_fileid2
            />
        }
    };
    
    let init_filters = Signal::derive(move || {
        vec![WhereCause {
            field_name: "hvid".to_string(),
            filter_items: vec![FliterItem {
                // 确保这里使用的是正确的 FilterItem 结构体名称
                operator: Operator::In,
                value: Some(selected_frid_run.get().to_string()),
            }],
            and_or: AndOr::And,
        }]
    });

    view!{
         <div class="flex flex-1 w-full h-full overflow-hidden bg-white">
            <div class="flex flex-col w-1/4 bg-gray-100 border-r border-gray-300">
                <div class="flex-1 p-4">
                    <FlowRunList menu_id wfid=3u32 on_row_select_change=on_row_select_change_run />
                </div>
            </div>
            <div class="flex flex-col w-1/4 bg-gray-100 border-r border-gray-300">
                <div class="flex-1 p-4">
                    <Suspense fallback=|| view! { <progress class="progress w-56"></progress> }>
                        <CommonPage
                            menu_id 
                            conf_name="hr_home_visit_empl" 
                            custom_buttons=custom_buttons 
                            on_row_select_change=on_row_select_change
                            is_refresh=is_refresh
                            init_filters=init_filters
                        />
                    </Suspense>
                </div>
            </div>
            <div class="flex flex-col flex-1 bg-gray-100 border-r border-gray-300 overflow-y-auto">
                <div class="flex-1 p-4">
                    {home_vist_file}
                </div>
            </div>
            // 提示信息容器
            <ToasterProvider position=ToastPosition::TopStart>
                {specialist_management}
                // {specialist_delete_management}
            </ToasterProvider>
        </div>
    }
}
